package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"vip-shop-hub/models/cache"
	"vip-shop-hub/models/mysql"
	"vip-shop-hub/pkg"
	"vip-shop-hub/viprpc/internal/svc"
	"vip-shop-hub/viprpc/viprpc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *viprpc.LoginRequest) (*viprpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Moble).Result()
	if result != in.CaptchaCode {
		return nil, errors.New("图形验证码错误,重新输入")
	}

	resul, _ := cache.Rdb.Get(l.ctx, "sms"+in.Moble).Result()
	if resul != in.SmsCode {
		return nil, errors.New("短信验证码错误,重新输入")
	}

	user := mysql.User{
		Model:     gorm.Model{},
		Moble:     in.Moble,
		Password:  pkg.Md5(in.Password),
		HeadImage: "https://img0.baidu.com/it/u=3530732730,4271362942&fm=253&fmt=auto&app=120&f=PNG?w=500&h=500",
		NickName:  fmt.Sprintf("用户_%d", rand.Intn(100000)),
	}

	if err := user.FindOrCreate(mysql.DB, in.Moble); err != nil {
		return nil, err
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误请重新输入")
	}
	login := &mysql.UserLogin{
		Model:  gorm.Model{},
		Mobile: in.Moble,
		Ip:     pkg.GetOutboundIP(),
	}
	if err := login.UserLoginCreate(mysql.DB); err != nil {
		logx.Error(err) //记录日志
	}
	cache.Rdb.Del(l.ctx, "sms"+user.Moble)
	cache.Rdb.Del(l.ctx, "captcha"+user.Moble)
	return &viprpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
